<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-panna-dialog_big'"
      :append-to-body="true"
      :title="sysBusinessSeal.sealTableInformation"
      align="center"
      :visible.sync="innerDialogFormVisible"
      @closed="cancel"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="sysBusinessSeal.sealName"
          :label-width="formLabelWidth"
          prop="sealName"
          :error="errorMsg.sealName"
        >
          <el-input v-model="formData.sealName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.informationEncoding"
          :label-width="formLabelWidth"
          prop="informationCoding"
          :error="errorMsg.informationCoding"
        >
          <el-input
            v-model="formData.informationCoding"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.circularText"
          :label-width="formLabelWidth"
          prop="annularText"
          :error="errorMsg.annularText"
        >
          <el-input
            v-model="formData.annularText"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.horizontalText"
          :label-width="formLabelWidth"
          prop="crosswiseText"
          :error="errorMsg.crosswiseText"
        >
          <el-input
            v-model="formData.crosswiseText"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item :label="sysBusinessSeal.belongingOrganization" prop>
          <BaseTreeMultiple
            v-model="formData.sealDepartment"
            :placeholder="operateType.pleaseSelect"
            :disabled="readOnly"
            :tree-data="depData"
          />
        </el-form-item>
        <el-form-item :label="sysBusinessSeal.head" prop="sealPrincipal">
          <el-select
            ref="selectDom"
            v-model="formData.sealPrincipal"
            :disabled="readOnly"
            multiple
            :placeholder="sysBusinessSeal.searchManager"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteUser"
            :loading="searchUserLoading"
            value-key="id"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.width"
          :label-width="formLabelWidth"
          prop="sealWidth"
          :error="errorMsg.sealWidth"
        >
          <el-input
            v-model="formData.sealWidth"
            type="number"
            min="0"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.height"
          :label-width="formLabelWidth"
          prop="sealHeight"
          :error="errorMsg.sealHeight"
        >
          <el-input
            v-model="formData.sealHeight"
            type="number"
            min="0"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.user"
          prop="sealUser"
          style="width: 100%"
        >
          <el-select
            ref="selectDom"
            v-model="formData.sealUser"
            :disabled="readOnly"
            multiple
            :placeholder="sysBusinessSeal.searchUsers"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteUser"
            :loading="searchUserLoading"
            value-key="id"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.sealIntroduction"
          :label-width="formLabelWidth"
          style="width: 100%"
          prop="introductionSeal"
          :error="errorMsg.introductionSeal"
        >
          <el-input
            v-model="formData.introductionSeal"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.sealImage"
          :label-width="formLabelWidth"
          prop="sealImgUrl"
          :error="errorMsg.sealImgUrl"
        >
          <BaseUpload
            key="BaseUploadAccountSignIcon"
            ref="BaseUploadAccountSignIcon"
            v-model="formData.sealImgUrl"
            :disabled="readOnly"
            business-type="90"
            :file-size="1024"
          />
        </el-form-item>
        <el-form-item
          :label="sysBusinessSeal.sealAttachment"
          :label-width="formLabelWidth"
          prop="sealAccessoryUrl"
          style="width: 100%"
          :error="errorMsg.sealAccessoryUrl"
        >
          <div style="float: left">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              multiple
              :limit="1"
              :file-list="fileList"
              :http-request="uploadFile"
              :on-preview="openFile"
            >
              <el-button size="small" type="primary">{{
                sysBusinessSeal.uploadAttachments
              }}</el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          type="primary"
          :disabled="!submitLoad"
          @click="onSubmit('formData')"
          >{{ operateType.save }}</el-button
        >
        <el-button @click="cancel">{{ operateType.cancel }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  get,
} from "../../../api/SysBusiness/SysBusinessSeal.js";
import { formatData } from "../../../utils/index";
import { formdataify } from "@/utils/index";
import {
  departmentTree,
  getUserListNoPage,
} from "../../../api/Permission/PermissionUserGroup.js";
import _ from "lodash";

export default {
  name: "SysBusinessSealEdit",

  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    sealId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      submitLoad: true,
      businessType: 91,
      fileList: [],
      userList: [],
      searchUserLoading: false,
      depData: [],
      loading: false,
      innerDialogFormVisible: false,
      formLabelWidth: "100px",
      initData: {
        id: 0,
        sealName: "",
        informationCoding: "",
        annularText: "",
        crosswiseText: "",
        introductionSeal: "",
        sealImgUrl: "",
        sealAccessoryUrl: "",
        sealState: 0,
        sealHeight: 0,
        sealWidth: 0,
      },
      formData: {
        id: 0,
        sealName: "",
        informationCoding: "",
        annularText: "",
        crosswiseText: "",
        introductionSeal: "",
        sealImgUrl: "",
        sealAccessoryUrl: "",
        sealState: 0,
        sealDepartment: [],
        sealPrincipal: [],
        sealUser: [],
        sealAccessoryName: "",
        sealHeight: "",
        sealWidth: "",
      },
      formDataRules: {
        sealName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        sealWidth: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
            message: this.$t("SysBusinessSeal.cannotBeNull"),
          },
        ],
        sealHeight: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
            message: this.$t("SysBusinessSeal.cannotBeNull"),
          },
        ],
      },
      initErrorMsg: {
        sealName: "",
        informationCoding: "",
        annularText: "",
        crosswiseText: "",
        introductionSeal: "",
        sealImgUrl: "",
        sealAccessoryUrl: "",
        sealState: "",
      },
      errorMsg: {
        sealName: "",
        informationCoding: "",
        annularText: "",
        crosswiseText: "",
        introductionSeal: "",
        sealImgUrl: "",
        sealAccessoryUrl: "",
        sealState: "",
      },
    };
  },
  computed: {
    operateType() {
      return this.$t("ModuleSysBusiness.OperateType") || {};
    },
    sysBusinessSeal() {
      return this.$t("SysBusinessSeal") || {};
    },
  },
  watch: {},
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    if (this.sealId) {
      get({ id: this.sealId }).then((res) => {
        this.formData = res.data;
        if (res.data.sealAccessoryName) {
          this.fileList.push({
            name: res.data.sealAccessoryName,
            url: res.data.sealAccessoryUrl,
          });
        }
        this.userList = res.data.allUser;
      });
    }
    departmentTree()
      .then((res) => {
        if (res.data.length) {
          this.depData = formatData(res.data);
        }
      })
      .catch(() => {
        this.loading = false;
      });
  },
  methods: {
    openFile(e) {
      // 设置连接
      var fileUrl = e.url;
      this.getBlob(fileUrl).then((blob) => {
        this.saveAs(blob, e.name);
      });
    },

    // 通过文件下载url拿到对应的blob对象
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };

        xhr.send();
      });
    },
    // 下载文件js模拟点击a标签进行下载
    saveAs(blob, filename) {
      var link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },

    uploadFile(params) {
      var file = params.file;
      var formData = new FormData();
      formData.append(file.name, file);
      const obj = {
        businessType: this.businessType,
        file: file,
      };
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        this.formData.sealAccessoryUrl = res.data.filePath;
        this.formData.sealAccessoryName = file.name;
      });
    },
    remoteUser(query) {
      this.searchUserLoading = true;
      getUserListNoPage({ name: query }).then((res) => {
        this.userList = res.data;
      });
      this.searchUserLoading = false;
    },
    cancel() {
      this.$emit("update:dialogFormVisible", false);
      this.$emit("update:sealId", "");
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },

    onSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.loading = true;
            this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
            if (this.formData.id <= 0) {
              create(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.submitLoad = true;

                    this.closeDialog();
                  } else {
                    this.submitLoad = true;

                    this.showValidateMsgCheck(res);
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.submitLoad = true;

                  this.loading = false;
                });
            } else {
              update(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.submitLoad = true;

                    this.closeDialog();
                  } else {
                    this.submitLoad = true;

                    this.showValidateMsgCheck(res);
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.submitLoad = true;

                  this.loading = false;
                });
            }
          } else {
            this.submitLoad = true;
            return false;
          }
        });
      }
    }, 2000),
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("sealName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "informationCoding",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("annularText", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("crosswiseText", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("introductionSeal", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("sealImgUrl", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("sealAccessoryUrl", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("sealState", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
